package com.zhongwang.mms.module.material.service;

import com.zhongwang.mms.gen.entity.MAdjustmentApply;
import com.zhongwang.mms.gen.entity.MInventory;
import com.zhongwang.mms.gen.entity.MOrderDetail;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.material.dao.MInventoryDao;
import com.zhongwang.mms.module.material.dao.MaterApplyDao;
import com.zhongwang.mms.module.material.model.MAdjustModel;
import com.zhongwang.mms.module.material.model.MinventorytModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.BigDecimalUtils;
import com.zhongwang.mms.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: 库存调整审批 服务层
 * @Author: China.mc
 * @Date: 2020/04/13 16:49
 */
@Service
public class MateApplyCheckService {

    @Autowired
    private MaterApplyDao materApplyDao;

    @Autowired
    private LogService logService;

    @Autowired
    private MInventoryService mInventoryService;

    @Autowired
    private MInventoryDao mInventoryDao;

    /**
     * 调整审核加载列表
     */
    public List<MAdjustModel> findProjectDailychenck(MAdjustModel madjustModel) {
        return materApplyDao.findProjectDailychenck(madjustModel);
    }

    /**
     * 根据adjid查询库存对比信息
     */
    public MAdjustModel findviewCheckId(MAdjustModel madjustModel) {
        return materApplyDao.findviewtDailyId(madjustModel);
    }

    /**
     * 提交审核通过数据
     */
    @Transactional
    public Integer updateauditpass(MAdjustModel madjustModel) {

        // 取得用户名称及时间
        Date checkDate = new Date();
        String checkUser = ShiroUtils.getUser().getName();

        //查询库存调整信息
        madjustModel = materApplyDao.selectByPrimaryKey(madjustModel);

        //查询原库存信息
        MInventory mInventory = materApplyDao.getMInventoryBuItyId(madjustModel.getAdjAfterItyId());

        //通过提交记录1查找同时生成的记录2
        MAdjustModel RecordTow = materApplyDao.findAdjByOderCodeTow(madjustModel);

        //盘点调整审核
        if (null != madjustModel.getAdjType() && madjustModel.getAdjType() == 2) {
            checkAdjustAppl(madjustModel.getAdjId());
        }
        //验证审核时，在库数量与可用数量不相等时不允许审核通过
        if (null != madjustModel.getAdjOditStatus() && madjustModel.getAdjOditStatus() == 2 && madjustModel.getAdjBeAfFlag() == 2 && !mInventory.getItyNum().equals(mInventory.getItyAvaNum())) {
            return 0;
        }
        //审核新增库存信息
        if (null != madjustModel.getAdjOditStatus() && madjustModel.getAdjOditStatus() == 1) {
            checkNewInventory(mInventory, madjustModel);
        }
        //调整物料与单位后审核出库记录
        if (null != RecordTow && null != RecordTow.getAdjOditStatus() && RecordTow.getAdjOditStatus() == 2 && RecordTow.getAdjBeAfFlag() == 2 && RecordTow.getAdjOrderCode() != null) {
            mInventory = materApplyDao.getMInventoryBuItyId(RecordTow.getAdjAfterItyId());
            checkRevInventory(mInventory, RecordTow);

            RecordTow.setAdjAuditDate(checkDate);
            RecordTow.setAdjAuditor(checkUser);
            materApplyDao.updateauditpass(RecordTow);
        }
        //调整物料与单位后审核入库记录
        if (null != madjustModel.getAdjOditStatus() && madjustModel.getAdjOditStatus() == 2 && madjustModel.getAdjBeAfFlag() == 1) {
            checkAudiStock(mInventory, madjustModel);
        }
        //审核库存数量调整(新改20200527)
        if (madjustModel.getAdjType().equals(1) && madjustModel.getAdjOditStatus() == null && madjustModel.getAdjOrderCode() == null && madjustModel.getAdjBeAfFlag() == null) {
            checkAudQuant(madjustModel);
        }

        madjustModel.setAdjAuditDate(checkDate);
        madjustModel.setAdjAuditor(checkUser);
        return materApplyDao.updateauditpass(madjustModel);
    }

    /**
     * 库存审核（批量审核）
     *
     * @param arr 明细Id集合
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String togetherAudit(List<Integer> arr) {
        String msg = "";  // 返回提示信息
        int successCount = 0; // 成功审核记录数
        int errorCount = 0; // 审核失败记录数
        MAdjustModel madjustModel;

        // 取得用户名称及时间
        Date checkDate = new Date();
        String checkUser = ShiroUtils.getUser().getName();
        for (int i = 0; i < arr.size(); i++) {

            madjustModel = new MAdjustModel();
            madjustModel.setAdjId(arr.get(i));
            //查询库存调整信息
            madjustModel = materApplyDao.selectByPrimaryKey(madjustModel);

            //查询原库存信息
            MInventory mInventory = materApplyDao.getMInventoryBuItyId(madjustModel.getAdjAfterItyId());

            //通过提交记录1查找同时生成的记录2
            MAdjustModel RecordTow = materApplyDao.findAdjByOderCodeTow(madjustModel);

            //盘点调整审核
            if (null != madjustModel.getAdjType() && madjustModel.getAdjType() == 2) {
                checkAdjustAppl(madjustModel.getAdjId());
            }
            //验证审核时，在库数量与可用数量不相等时不允许审核通过
            if (null != madjustModel.getAdjOditStatus() && madjustModel.getAdjOditStatus() == 2 && madjustModel.getAdjBeAfFlag() == 2 && !mInventory.getItyNum().equals(mInventory.getItyAvaNum())) {
                errorCount++;
                continue;
            }
            //审核新增库存信息
            if (null != madjustModel.getAdjOditStatus() && madjustModel.getAdjOditStatus() == 1) {
                checkNewInventory(mInventory, madjustModel);
            }
            //调整物料与单位后审核出库记录
            if (null != RecordTow && null != RecordTow.getAdjOditStatus() && RecordTow.getAdjOditStatus() == 2 && RecordTow.getAdjBeAfFlag() == 2 && RecordTow.getAdjOrderCode() != null) {
                mInventory = materApplyDao.getMInventoryBuItyId(RecordTow.getAdjAfterItyId());
                checkRevInventory(mInventory, RecordTow);

                RecordTow.setAdjAuditDate(checkDate);
                RecordTow.setAdjAuditor(checkUser);
                materApplyDao.updateauditpass(RecordTow);
            }
            //调整物料与单位后审核入库记录
            if (null != madjustModel.getAdjOditStatus() && madjustModel.getAdjOditStatus() == 2 && madjustModel.getAdjBeAfFlag() == 1) {
                checkAudiStock(mInventory, madjustModel);
            }
            //审核库存数量调整(新改20200527)
            if (madjustModel.getAdjType().equals(1) && madjustModel.getAdjOditStatus() == null && madjustModel.getAdjOrderCode() == null && madjustModel.getAdjBeAfFlag() == null) {
                checkAudQuant(madjustModel);
            }
            madjustModel.setAdjAuditDate(checkDate);
            madjustModel.setAdjAuditor(checkUser);
            materApplyDao.updateauditpass(madjustModel);
        }

        logService.saveLog("库存调整审批", "审批成功：" + (arr.size() - errorCount) + "条, 审批失败：" + errorCount + "条");
        msg = "" + errorCount + "条数据审核失败。<br>原因：在库数量与可用数量不等，不能调整该记录。需要先查看可用数量！";
        return errorCount > 0 ? msg : "审核通过！";

    }

    /**
     * 调整审核时审批盘点数据
     *
     * @param adjId
     */
    @Transactional
    public void checkAdjustAppl(Integer adjId) {

        double totalNum;
        double totalWeight;
        MAdjustModel madjustModel = materApplyDao.selectByInventory(adjId);
        MAdjustmentApply mAdjustmentApply = new MAdjustmentApply();
        MOrderDetail mOrderDetail = new MOrderDetail();
        User user = ShiroUtils.getUser();
        String ajaAuditor = user.getName();
        //盘点审核判断 1 盘盈 2 盘亏
        if (null != madjustModel.getAdjPalValStatus() && madjustModel.getAdjPalValStatus() == 2) {
            MInventory mInventory = materApplyDao.getMInventoryBuItyId(madjustModel.getAdjAfterItyId());
            totalNum = mInventory.getItyNum();
            totalWeight = mInventory.getItyWeight();
            mAdjustmentApply.setAjaItyNum(totalNum);
            mAdjustmentApply.setAjaItyWeight(totalWeight);
            //盘盈时更新库存信息
            mInventory.setItyNum(BigDecimalUtils.sub(mInventory.getItyNum(), madjustModel.getAdjNum() != null ? madjustModel.getAdjNum() : 0.0));
            mInventory.setItyWeight(BigDecimalUtils.sub(mInventory.getItyWeight(), madjustModel.getAdjWeight() != null ? madjustModel.getAdjWeight() : 0.0));
            mInventoryDao.updateByPrimaryKey(mInventory);
            //将盘亏数据插入出入库明细表进行出库
            mOrderDetail.setOdaInType(madjustModel.getAdjInType());
            mOrderDetail.setOdaProCode(madjustModel.getAdjProjectCode());
            mOrderDetail.setOdaProName(madjustModel.getAdjProjectName());
            mOrderDetail.setOdaNum(madjustModel.getAdjNum());
            mOrderDetail.setOdaWeight(madjustModel.getAdjWeight());
            mOrderDetail.setOdaTrackCode(madjustModel.getAdjTrackCode());
            mOrderDetail.setOdaMatId(madjustModel.getAdjAfterMatId());
            mOrderDetail.setOdaSpec(madjustModel.getAdjSpec());
            mOrderDetail.setOdaPrice(madjustModel.getAdjPrice());
            mOrderDetail.setOdaBackDate(madjustModel.getAdjBackDate());
            mOrderDetail.setOdaAmount(madjustModel.getAdjAmount());
            mOrderDetail.setOdaItyId(mInventory.getItyId());
            mOrderDetail.setOdaType(2);
            materApplyDao.insertMorder(mOrderDetail);
        } else if (null != madjustModel.getAdjPalValStatus() && madjustModel.getAdjPalValStatus() == 1) {
            //判断盘盈物料信息审核更新库存表与出入表
            MInventory newmInventory = new MInventory();
            newmInventory.setItyInType(madjustModel.getAdjInType());
            newmInventory.setItyMatId(madjustModel.getAdjAfterMatId());
            newmInventory.setItyProName(madjustModel.getAdjProjectName());
            newmInventory.setItyNum(madjustModel.getAdjNum());
            newmInventory.setItyWeight(madjustModel.getAdjWeight());
            newmInventory.setItyAvaNum(madjustModel.getAdjNum());
            newmInventory.setItyAvaWeight(madjustModel.getAdjWeight());
            newmInventory.setItyPrice(madjustModel.getAdjPrice());
            newmInventory.setItyStoId(11);
            newmInventory.setItyTrackCode("");
            newmInventory.setItyProCode("");
            newmInventory.setItySpec("");
            newmInventory = mInventoryService.addInventory(newmInventory, 1);
            //将盘盈库存插入出入库表进行入库
            mOrderDetail.setOdaInType(madjustModel.getAdjInType());
            mOrderDetail.setOdaProCode(madjustModel.getAdjProjectCode());
            mOrderDetail.setOdaProName(madjustModel.getAdjProjectName());
            mOrderDetail.setOdaNum(madjustModel.getAdjNum());
            mOrderDetail.setOdaWeight(madjustModel.getAdjWeight());
            mOrderDetail.setOdaTrackCode(madjustModel.getAdjTrackCode());
            mOrderDetail.setOdaMatId(madjustModel.getAdjAfterMatId());
            mOrderDetail.setOdaSpec(madjustModel.getAdjSpec());
            mOrderDetail.setOdaPrice(madjustModel.getAdjPrice());
            mOrderDetail.setOdaBackDate(madjustModel.getAdjBackDate());
            mOrderDetail.setOdaAmount(madjustModel.getAdjAmount());
            mOrderDetail.setOdaItyId(newmInventory.getItyId());
            mOrderDetail.setOdaType(1);
            materApplyDao.insertMorder(mOrderDetail);
            totalNum = BigDecimalUtils.sub(newmInventory.getItyNum(), madjustModel.getAdjNum());
            totalWeight = BigDecimalUtils.sub(newmInventory.getItyWeight(), madjustModel.getAdjWeight());
            mAdjustmentApply.setAjaItyNum(totalNum);
            mAdjustmentApply.setAjaItyWeight(totalWeight);
        }
        //审核通过后回写盘点损益调整表
        mAdjustmentApply.setAjaItyStatus(4);
        mAdjustmentApply.setAjaAuditDate(new Date());
        mAdjustmentApply.setAjaAuditor(ajaAuditor);
        mAdjustmentApply.setAjaId(madjustModel.getAdjAjaId());
        materApplyDao.updateByExample(mAdjustmentApply);

    }

    /**
     * 审核新增库存信息
     */
    @Transactional
    public void checkNewInventory(MInventory mInventory, MAdjustModel madjustModel) {
        //实例化库存信息
        MOrderDetail mOrderDetail = new MOrderDetail();
        mInventory = new MInventory();
        mInventory.setItyProCode(madjustModel.getAdjProjectCode());
        mInventory.setItyProName(madjustModel.getAdjProjectName());
        mInventory.setItyMatId(madjustModel.getAdjAfterMatId());
        mInventory.setItyTrackCode(madjustModel.getAdjTrackCode());
        mInventory.setItySpec(madjustModel.getAdjSpec());
        mInventory.setItyInType(madjustModel.getAdjInType());
        mInventory.setItyNum(madjustModel.getAdjAfterNum());
        mInventory.setItyWeight(madjustModel.getAdjAfterWeight());
        mInventory.setItyPrice(madjustModel.getAdjPrice());
        mInventory.setItyAvaNum(madjustModel.getAdjAfterNum());
        mInventory.setItyAvaWeight(madjustModel.getAdjAfterWeight());
        if(madjustModel.getMsName()!=null){
            mInventory.setItyStoId(madjustModel.getMsName());
        }
        //mInventory.setItyStoId(mInventory.getItyStoId());
        mInventory = mInventoryService.addInventory(mInventory, 1);
        //将新增库存信息插入出入库表中
        mOrderDetail.setOdaInType(madjustModel.getAdjInType());
        mOrderDetail.setOdaProCode(madjustModel.getAdjProjectCode());
        mOrderDetail.setOdaProName(madjustModel.getAdjProjectName());
        mOrderDetail.setOdaNum(madjustModel.getAdjAfterNum());
        mOrderDetail.setOdaWeight(madjustModel.getAdjAfterWeight());
        mOrderDetail.setOdaTrackCode(madjustModel.getAdjTrackCode());
        mOrderDetail.setOdaMatId(madjustModel.getAdjAfterMatId());
        mOrderDetail.setOdaSpec(madjustModel.getAdjSpec());
        mOrderDetail.setOdaPrice(madjustModel.getAdjPrice());
        mOrderDetail.setOdaBackDate(madjustModel.getAdjBackDate());
        mOrderDetail.setOdaAmount(madjustModel.getAdjAmount());
        mOrderDetail.setOdaItyId(mInventory.getItyId());
        mOrderDetail.setOdaType(1);
        materApplyDao.insertMorder(mOrderDetail);
    }

    /**
     * 物料调整后审核需要出库记录
     */
    @Transactional
    public void checkRevInventory(MInventory mInventory, MAdjustModel RecordTow) {
        MOrderDetail mOrderDetail = new MOrderDetail();
        mInventory.setItyId(RecordTow.getAdjAfterItyId());
        mInventory.setItyNum(RecordTow.getAdjAfterNum());
        mInventory.setItyWeight(RecordTow.getAdjAfterWeight());
        mInventory.setItyAvaNum(Double.valueOf(0));
        mInventory.setItyAvaWeight(Double.valueOf(0));
        materApplyDao.updateAddhInventory(mInventory);
        mOrderDetail.setOdaInType(RecordTow.getAdjInType());
        mOrderDetail.setOdaProCode(RecordTow.getAdjProjectCode());
        mOrderDetail.setOdaProName(RecordTow.getAdjProjectName());
        mOrderDetail.setOdaNum(RecordTow.getAdjBeforeNum());
        mOrderDetail.setOdaWeight(RecordTow.getAdjBeforeWeight());
        mOrderDetail.setOdaTrackCode(RecordTow.getAdjTrackCode());
        mOrderDetail.setOdaMatId(RecordTow.getAdjAfterMatId());
        mOrderDetail.setOdaSpec(RecordTow.getAdjSpec());
        mOrderDetail.setOdaPrice(RecordTow.getAdjPrice());
        mOrderDetail.setOdaBackDate(RecordTow.getAdjBackDate());
        mOrderDetail.setOdaAmount(RecordTow.getAdjAmount());
        mOrderDetail.setOdaItyId(mInventory.getItyId());
        mOrderDetail.setOdaType(2);
        materApplyDao.insertMorder(mOrderDetail);
    }

    /**
     * 物料调整后审核需要入库记录
     */
    @Transactional
    public void checkAudiStock(MInventory mInventory, MAdjustModel madjustModel) {
        MOrderDetail mOrderDetail = new MOrderDetail();
        mInventory = new MInventory();
        mInventory.setItyProCode(madjustModel.getAdjProjectCode());
        mInventory.setItyProName(madjustModel.getAdjProjectName());
        mInventory.setItyMatId(madjustModel.getAdjAfterMatId());
        mInventory.setItyTrackCode(madjustModel.getAdjTrackCode());
        mInventory.setItySpec(madjustModel.getAdjSpec());
        mInventory.setItyInType(madjustModel.getAdjInType());
        mInventory.setItyNum(madjustModel.getAdjAfterNum());
        mInventory.setItyWeight(madjustModel.getAdjAfterWeight());
        mInventory.setItyPrice(madjustModel.getAdjPrice());
        mInventory.setItyAvaNum(madjustModel.getAdjAfterNum());
        mInventory.setItyAvaWeight(madjustModel.getAdjAfterWeight());
        mInventory.setItyStoId(madjustModel.getMsName());
        mInventoryService.addInventory(mInventory, 1);
        mOrderDetail.setOdaInType(madjustModel.getAdjInType());
        mOrderDetail.setOdaProCode(madjustModel.getAdjProjectCode());
        mOrderDetail.setOdaProName(madjustModel.getAdjProjectName());
        mOrderDetail.setOdaNum(madjustModel.getAdjAfterNum());
        mOrderDetail.setOdaWeight(madjustModel.getAdjAfterWeight());
        mOrderDetail.setOdaTrackCode(madjustModel.getAdjTrackCode());
        mOrderDetail.setOdaMatId(madjustModel.getAdjAfterMatId());
        mOrderDetail.setOdaSpec(madjustModel.getAdjSpec());
        mOrderDetail.setOdaPrice(madjustModel.getAdjPrice());
        mOrderDetail.setOdaBackDate(madjustModel.getAdjBackDate());
        mOrderDetail.setOdaAmount(madjustModel.getAdjAmount());
        mOrderDetail.setOdaItyId(mInventory.getItyId());
        mOrderDetail.setOdaType(1);
        materApplyDao.insertMorder(mOrderDetail);
    }

    /**
     * 调整库存信息在库数量
     */
    private void checkAudQuant(MAdjustModel madjustModel) {
        MinventorytModel minventorytModel = new MinventorytModel();
        minventorytModel.setItyId(madjustModel.getAdjAfterItyId());
        minventorytModel = materApplyDao.selectByExample(minventorytModel);
        minventorytModel.setItyNum(minventorytModel.getItyNum() + (madjustModel.getAdjAfterNum() - madjustModel.getAdjBeforeNum()));
        minventorytModel.setItyWeight(minventorytModel.getItyWeight() + (madjustModel.getAdjAfterWeight() - madjustModel.getAdjBeforeAvaWeight()));
        minventorytModel.setItyAvaNum(minventorytModel.getItyAvaNum() + (madjustModel.getAdjAfterNum() - madjustModel.getAdjBeforeNum()));
        minventorytModel.setItyAvaWeight(minventorytModel.getItyAvaWeight() + (madjustModel.getAdjAfterWeight() - madjustModel.getAdjBeforeAvaWeight()));
        materApplyDao.updateAddMinvent(minventorytModel);
    }

    /**
     * 提交调整审核不通过
     */
    public Integer updateauditfailed(MAdjustModel madjustModel) {
        // 取得用户名称及时间
        Date checkDate = new Date();
        String checkUser = ShiroUtils.getUser().getName();

        MAdjustModel checkUpdateID = materApplyDao.findAdjByOderCode(madjustModel.getAdjId());
        madjustModel.setAdjOrderCode(checkUpdateID.getAdjOrderCode());
        MAdjustModel checkUpdateIDB = materApplyDao.findAdjByOderCodeTow(madjustModel);
        if (checkUpdateIDB != null) {
            checkUpdateIDB.setAdjAuditDate(checkDate);
            checkUpdateIDB.setAdjAuditor(checkUser);
            materApplyDao.updateauditfailed(checkUpdateIDB);
        }

        checkUpdateID.setAdjAuditDate(checkDate);
        checkUpdateID.setAdjAuditor(checkUser);
        return materApplyDao.updateauditfailed(checkUpdateID);
    }


}











